<template>
  <div class="JustCard">
    <div class="justItem">
      <div v-if="dbCategory.length>0">
        <el-row :gutter="24">
          <el-col
            :span="5"
            v-for="(o, index) in dbCategory"
            style="margin:10px"
            :key="index"
            :offset="index > 0 ? 1 : 0"
          >
            <el-card
              shadow="hover"
              :body-style="{ padding: '5px',margin:'10px', cursor: 'pointer',position:'relative' }"
            >
              <p style="position:absolute;right:10px;top:-10px;color:#409eff">
                <el-popover placement="bottom" width="30" trigger="click">
                  <div class="popBox">
                    <el-tooltip class="item" effect="dark" content="编辑" placement="right">
                      <i class="el-icon-edit-outline" @click.stop.prevent="editCard(o)"></i>
                    </el-tooltip>
                  </div>
                  <div class="popBox">
                    <el-tooltip class="item" effect="dark" content="删除" placement="right">
                      <i class="el-icon-delete" @click.stop.prevent="deleteTable(o)"></i>
                    </el-tooltip>
                  </div>
                  <span slot="reference" class="jstarfont jstar-gengduo finger"></span>
                </el-popover>
              </p>

              <img :src="o.imgUrl" class="image" @click="goDbIndex(o)" />
              <div>
                <p>
                  数据库名称：
                  <span>{{o.dbName}}</span>
                </p>
                <p>
                  占用空间：
                  <span>{{o.occupiedSpaceCount}} /K</span>
                </p>
                <p>
                  用户：
                  <span>{{o.userCount}}</span>
                </p>
                <p>
                  表数量：
                  <span>{{ o.tableCount }}</span>
                </p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <div v-else>
        <el-empty description="暂无数据库，请往右侧添加按钮添加"></el-empty>
      </div>
    </div>
    <div class="justAdd">
      <el-tooltip class="iconTip" effect="dark" content="添加入库" placement="right">
        <i class="el-icon-plus" @click="addCategory()"></i>
      </el-tooltip>
    </div>

    <!--添加弹窗 -->
    <el-dialog :title="isEdit ? '修改数据库' : '添加数据库'" :visible.sync="dialogVisible" width="40%">
      <div>
        <el-form :model="dbData" label-width="250px" :rules="addDbDataRules" ref="dbData">
          <!-- <el-form-item label="数据库别名:" prop="aliasName">
            <el-input style="width:250px" v-model="dbData.aliasName"></el-input>
          </el-form-item>-->

          <!-- <el-form-item label="数据库名称:" prop="dbName">
            <el-input style="width: 250px" v-model="dbData.dbName"></el-input>
          </el-form-item>-->

          <el-form-item label="id" prop="id" style="display:none">
            <el-input style="width: 250px" v-model="dbData.id"></el-input>
          </el-form-item>

          <el-form-item label="驱动:" prop="dbDriver">
            <el-input style="width:250px" v-model="dbData.dbDriver"></el-input>
          </el-form-item>

          <el-form-item label="数据库类型:" prop="dbType">
            <el-input style="width: 250px" v-model="dbData.dbType"></el-input>
          </el-form-item>

          <el-form-item label="连接串:" prop="dbUrl">
            <el-input style="width: 250px" v-model="dbData.dbUrl"></el-input>
          </el-form-item>

          <el-form-item label="账号:" prop="username">
            <el-input style="width: 250px" v-model="dbData.username"></el-input>
          </el-form-item>

          <el-form-item label="密码:" prop="password">
            <el-input show-password style="width: 250px" v-model="dbData.password"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer">
        <el-button @click="testBtn('dbData')">测试连接</el-button>
        <el-button type="primary" @click="submitAddValue('dbData')">确定提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import localStorage from '@/utils/localStorage'
export default {
  data() {
    return {
      currentDate: new Date(),
      dbCategory: '',
      popoverWidth: '30',
      isEdit: false,
      addDbDataRules: {
        // aliasName: [
        //   { required: true, message: '请输入数据库别名', trigger: 'blur' },
        // ],
        dbDriver: [
          { required: true, message: '请输入数据库驱动', trigger: 'blur' },
        ],
        // dbName: [
        //   { required: true, message: '请输入数据库名称', trigger: 'blur' },
        // ],
        dbType: [
          { required: true, message: '请输入数据库类型', trigger: 'blur' },
        ],
        dbUrl: [
          { required: true, message: '请输入数据库连接串', trigger: 'blur' },
        ],
        username: [
          { required: true, message: '请输入数据库账号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入数据库密码', trigger: 'blur' },
        ],
      },
      dbData: {
        aliasName: 'mysql',
        dbDriver: 'com.mysql.cj.jdbc.Driver',
        dbName: 'mysql',
        dbType: 'mysql',
        dbUrl:
          'jdbc:mysql://192.168.8.140:3306/pinxin_saas?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true',
        username: '',
        password: '',
        id: '',
      },
      dialogVisible: false,
    }
  },
  created() {
    this.goDbServe()
  },
  methods: {
    goDbServe() {
      this.$db.getDbTable().then((res) => {
        if (res.code == 200) {
          this.dbCategory = res.data
        } else {
          this.$message.error(res.code + '-' + res.msg)
        }
      })
    },

    goDbIndex(o) {
      console.log(o)
      localStorage.set('dbSecrekey', o.dbId)
      localStorage.set('dbItem', o.dbName)
      localStorage.set('db', o)
      this.$router.push({
        path: '/dbConfig/index',
      })
    },

    /* 新建目录 */
    addCategory() {
      this.dbData.aliasName = 'mysql1'
      this.dbData.dbDriver = 'com.mysql.cj.jdbc.Driver'
      this.dbData.dbName = 'mysql1'
      this.dbData.dbType = 'mysql'
      this.dbData.dbUrl =
        'jdbc:mysql://192.168.8.140:3306/pinxin_saas?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true'
      this.dbData.username = 'root'
      this.dbData.password = 'root'
      this.dbData.id = ''
      this.isEdit = false
      this.dialogVisible = true
    },

    //编辑库
    editCard(o) {
      this.isEdit = true
      console.log(o)
      this.dialogVisible = true
      this.dbData.aliasName = o.aliasName
      this.dbData.dbDriver = o.dbDriver
      this.dbData.dbName = o.dbName
      this.dbData.dbType = o.dbType
      this.dbData.dbUrl = o.dbUrl
      this.dbData.username = o.username
      this.dbData.password = o.password
      this.dbData.id = o.id
    },

    //添加数据库
    submitAddValue(formName) {
      console.log(this.dbData.id)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this[formName]))
          if (this.dbData.id) {
            params = {
              id: this.dbData.id,
              params: {
                aliasName: this.dbData.aliasName,
                dbDriver: this.dbData.dbDriver,
                ddbName: this.dbData.dbName,
                dbType: this.dbData.dbType,
                dbUrl: this.dbData.dbUrl,
                username: this.dbData.username,
                password: this.dbData.password,
              },
            }
          } else {
            params = this.dbData
          }
          let apiName = this.isEdit ? 'patchDbTable' : 'addDbConnect'
          this.$db[apiName](params)
            .then((res) => {
              if (res.code === 200) {
                this.dbSecrekey = res.data
                console.log(this.dbSecrekey)
                localStorage.set('dbSecrekey', this.dbSecrekey)
                this.dialogVisible = false
                this.goDbServe()
                this.$message.success('成功！')
              } else {
                this.$message.error(res.code + '-' + res.msg)
              }
            })
            .catch((e) => {
              this.$message.error(e.toString())
            })
        }
      })
    },

    testBtn(formName) {
      console.log(this.dbData.id)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this[formName]))
          params = {
            aliasName: this.dbData.aliasName,
            dbDriver: this.dbData.dbDriver,
            ddbName: this.dbData.dbName,
            dbType: this.dbData.dbType,
            dbUrl: this.dbData.dbUrl,
            username: this.dbData.username,
            password: this.dbData.password,
          }
          this.$db
            .getDbTest(params)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success('通过,可以添加！')
              } else {
                this.$message.error(res.code + '-' + res.msg)
              }
            })
            .catch((e) => {
              this.$message.error(e.toString())
            })
        }
      })
    },

    //删除
    deleteTable(o) {
      console.log(o)
      this.$confirm('是否删除 ' + o.aliasName + ' 参数?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let params = {
          id: o.id,
        }
        this.$db.delDbTable(params).then((res) => {
          if (res.code === 200) {
            this.$message.success('删除' + o.aliasName + '成功！')
            this.goDbServe()
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
      })
    },
  },
}
</script>

<style  lang="less">
.JustCard {
  .popBox {
    display: flex;
    flex-direction: column;
    // justify-content: space-between;
    align-items: center;
    // height: 60px;
    i {
      margin-bottom: 10px;
    }
  }
  .el-row {
    width: 98%;
    float: left;
    .image {
      width: 100%;
      height: 200px;
    }
    span {
      color: rgb(0, 110, 255);
    }
  }
  .justAdd {
    float: left;
    width: 2%;
    margin-top: 20px;
    .el-icon-plus {
      color: #409eff;
      font-size: 30px;
    }
  }
  .justItem {
    float: left;
    width: 98%;
    min-height: 500px;
  }
}
</style>